//
//  JoymengRate.m
//  GameChooser
//
//  Created by Moonwolf on 14-1-23.
//  Copyright (c) 2014年 moonwolf. All rights reserved.
//

#import "JoymengRate.h"

@implementation JoymengRate
+ (int) numberOfExecutions {
    return [[NSUserDefaults standardUserDefaults] integerForKey:kJM_RUNCOUNT];
}

- (id) initWithNumberOfExecutions:(int) executionCount {
    if ((self = [super init])) {
        numberOfExecutions = executionCount;
    }
    
    return self;
}
+(void)clearData
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    
    [standardDefaults setInteger:0 forKey:kJM_RUNCOUNT];
    [standardDefaults synchronize];
}
+(void)load
{
    @autoreleasepool {

    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    
    int numberOfExecutions = [standardDefaults integerForKey:kJM_RUNCOUNT] + 1;
    
    
    [[[JoymengRate alloc] initWithNumberOfExecutions:numberOfExecutions] performSelector:@selector(setup) withObject:Nil afterDelay:1.0];
    
    [standardDefaults setInteger:numberOfExecutions forKey:kJM_RUNCOUNT];
    [standardDefaults synchronize];
    }
}

- (void) setup {
    NSDictionary *bundleDictionary = [[NSBundle mainBundle] infoDictionary];
    
    if (numberOfExecutions == [[bundleDictionary objectForKey:kJM_RUNCOUNT] intValue]) {
        NSString *title = NSLocalizedString([bundleDictionary objectForKey:kJM_TITLE], Nil);
        NSString *message = NSLocalizedString([bundleDictionary objectForKey:kJM_MESSAGE], Nil);
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                             message:message
                                                            delegate:self
                                                   cancelButtonTitle:@"No"
                                                  otherButtonTitles:@"YES", Nil];;
        [alertView show];
    }
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSString *appId = [[[NSBundle mainBundle] infoDictionary] objectForKey:kJM_APPID];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://userpub.itunes.apple.com/WebObjects/MZUserPublishing.woa/wa/addUserReview?id=%@&type=Purple+Software", appId]]];
    }
}
- (void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    [self release];
}
-(void)dealloc
{
    [super dealloc];
}
@end
